# -*- coding: utf-8 -*-
import json,requests
from fullstack import app,api,db
from flask import Flask,jsonify,Response,request,session,g
from flask_restful import Resource
from fullstack.Models.member.Member import Member
from fullstack.Models.food.WxShareHistory import WxShareHistory
from fullstack.Models.member.OauthMemberBind import OauthMemberBind
from fullstack.WeChat.Service.MemberService import MemberService
from fullstack.utils import getCurrentTime


SECTION_URL='/wechat/api/member'


class CheckReg(Resource):
    def post(self):
        resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
        req = request.values
        code = req['code'] if 'code' in req else ''
        if not code or len(code) < 1:
            resp['code'] = -1
            resp['msg'] = "需要code"
            return jsonify(resp)

        openid = MemberService.getWeChatOpenId(code)
        if openid is None:
            resp['code'] = -1
            resp['msg'] = "调用微信出错"
            return jsonify(resp)

        bind_info = OauthMemberBind.query.filter_by(openid=openid, type=1).first()
        if not bind_info:
            resp['code'] = -1
            resp['msg'] = "未绑定"
            return jsonify(resp)

        member_info = Member.query.filter_by( id = bind_info.member_id).first()
        if not member_info:
            resp['code'] = -1
            resp['msg'] = "未查询到绑定信息"
            return jsonify(resp)

        token = "%s#%s"%( MemberService.geneAuthCode( member_info ),member_info.id )
        resp['data'] = { 'token':token }
        return jsonify(resp)

api.add_resource(CheckReg,SECTION_URL+'/check-reg')


class MemberShare(Resource):
    def post(self): 
        resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
        req = request.values
        url = req['url'] if 'url' in req else ''
        member_info = g.member_info
        model_share = WxShareHistory()
        if member_info:
            model_share.member_id = member_info.id
        model_share.share_url = url
        model_share.created_time = getCurrentTime()
        db.session.add(model_share)
        db.session.commit()
        return jsonify(resp)

api.add_resource(MemberShare,SECTION_URL+'/share')


class MemberInfo(Resource):
    def get(self):
        resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
        member_info = g.member_info
        resp['data']['info'] = {
            "nickname":member_info.nickname,
            "avatar_url":member_info.avatar
        }
        return jsonify(resp)

api.add_resource(MemberInfo,SECTION_URL+'/info')